package com.myProject.control.message;

import com.myProject.bean.TInsect;
import com.myProject.serves.Impl.InsectSevImpl;
import com.myProject.serves.InsectSev;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet(name = "InsectServlet", urlPatterns = "/insect")
public class InsectServlet extends HttpServlet {
    InsectSev is = new InsectSevImpl();

    /**
     * @param request
     * @param response
     * @return void
     * @author liuyulai
     * @date 21.4.29 10:28
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * @param request
     * @param response
     * @return void
     * @author liuyulai
     * @date 21.4.29 10:28
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String med = request.getParameter("method");
        System.out.println("med = " + med);
        if (med == null || "".equalsIgnoreCase(med)) {
            showAll(request, response);
        } else if ("add".equalsIgnoreCase(med)) {
            addInsect(request, response);
        } else if ("addPic".equalsIgnoreCase(med)) {
            try {
                addPic(request, response);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }
    }

    private void addPic(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
        String realPath = this.getServletContext().getRealPath("/LayUiBac/upload");
        File file = new File(realPath);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("此目录不存在");
            file.mkdir();
        }
        String value = null;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //解决乱码
        upload.setHeaderEncoding("UTF-8");

        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }
        //设置上传文件大小
        upload.setFileSizeMax(1024 * 1024 * 10);
        List<FileItem> list = upload.parseRequest(request);

        for (FileItem fileItem : list) {
            if (!fileItem.isFormField()) {
                String fileName = fileItem.getName();
                if (fileName == null || "".equals(fileName.trim())) {
                    continue;
                }
                //将文件地址获取后截取文件名称
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                //通过流将文件放入项目的文件夹中
                InputStream in = fileItem.getInputStream();

                FileOutputStream out = new FileOutputStream(realPath + "/" + fileName);
                //数据库的值，但是暂时不会保存到数据库，需要先进行前台传输
                value = "/Trees/LayUiBac/upload/" + fileName;
                //输出流操作
                byte buffer[] = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                fileItem.delete();
            }
        }
        //返回格式需要是json并且格式有要求
        String json = "{\"code\":0,\"msg\":\"\",\"data\":{\"path\":\"" + value + "\"}}";
        System.out.println("json=" + json);
        response.getWriter().write(json);
    }

    private void addInsect(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("insectName");
        String host = request.getParameter("host");
        String danger = request.getParameter("danger");
        String enemy = request.getParameter("enemy");
        String breed = request.getParameter("breed");
        String step = request.getParameter("step");
        String picture = request.getParameter("picUp");
        TInsect t = new TInsect();
        t.setName(name);
        t.setHost(host);
        t.setDanger(danger);
        t.setBreed(breed);
        t.setEnemy(enemy);
        t.setStep(step);
        t.setPicture(picture);
        is.addInsect(t);
    }

    private void showAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        int pageNo = 1;
        String Page = request.getParameter("page");
        if (Page != null) {
            pageNo = Integer.parseInt(Page);
        }
        System.out.println("pageNo = " + pageNo);
        String limit = request.getParameter("limit");
        int pageSize = Integer.parseInt(limit);
        String insectName = request.getParameter("insectName");
        String host = request.getParameter("host");
        TInsect t = new TInsect();
        t.setName(insectName);
        t.setHost(host);
        PageInfo<TInsect> show = is.showInsectByPage(pageNo, pageSize, t);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(show);
        System.out.println("json = " + json);
        pw.write(json);

    }
}
